public class Leet1254 {
    public static void main(String[] args) {
        System.out.println(closedIsland(new int[][]{{1,1,1},{1,0,1},{0,1,0}}));
    }
    static boolean flag;
    static public int closedIsland(int[][] grid) {
        int num = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j]==0){
                    flag = false;
                    dfs(grid,i,j);
                    if(!flag)
                        num++;
                    else
                        flag = false;
                }
            }
        }
        return num;
    }
    static void dfs(int[][] grid,int i ,int j){
        if(i==0||i==grid.length-1||j==0||j==grid[0].length-1){
            flag = true;
            return;
        }
        grid[i][j] = 3;
        if (grid[i+1][j]==0)
            dfs(grid,i+1,j);
        if (grid[i-1][j]==0)
            dfs(grid,i-1,j);
        if (grid[i][j+1]==0)
            dfs(grid,i,j+1);
        if (grid[i][j-1]==0)
            dfs(grid,i,j-1);
    }
}
